﻿package com.zuzhili.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.dispatcher.http.HttpHelperWraper.HttpRequestParam;

public class CacheDataCtrl extends DataCtrlBase{
	public class CacheType{
		public final static int UnPickOrders_Cache=0;
		public final static int MyOrders_Cache=1;
		public final static int Senders_Cache=2;
		public final static int SendedOrders_Cache=3;
		public final static int Gifts_Cache=0;
		
		
	}
	public final static class Colums{
		static String table="cache";
		
		static String _id="_id";
		static String cachetype="cachetype";
		static String jsondata="jsondata";
		static String time="time";
		static String identify="identify";
	}
	private final static String DB_CreateTable = "create table if not exists "+Colums.table+" (" +
			Colums._id+" INTEGER PRIMARY KEY," +
			Colums.cachetype+" smallint," +
			Colums.identify+"  VARCHAR(255)," +
			Colums.jsondata+" TEXT," +
			Colums.time+" INTEGER )";
	
	private static String DB_CreateIdx1 = "create unique index idxcache on "+Colums.table+" ("+Colums.cachetype+","+Colums.identify+")";
	
	
	//common func
	public void onCreate(SQLiteDatabase db){
		m_db=db;
		db.execSQL( DB_CreateTable );
		
		db.execSQL( DB_CreateIdx1 );
	}
	public void onUpgrade(SQLiteDatabase db,int oldv,int newv){
		m_db=db;
		if(newv<=oldv){
			return;
		}
		if(oldv<6){
			db.execSQL( DB_CreateTable );
			try{
				
				db.execSQL( DB_CreateIdx1 );
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
	
	//bussness func
	public void insertRec(HttpRequestParam param){
		String start=(String)param.nodesrequest.get("begin");
		if(start==null || !start.equals("0")){
			return;
		}
		CacheDataRec rec=new CacheDataRec();
		rec.cachetype=param.cachetype+"";
		rec.identify=param.identify;
		rec.jsondata=param.jsonstr;
		Log.e("liu", "insert to cache");
		Log.e("liu", "cachetype: " + param.cachetype + " identity: " + param.identify + " jsonstr: " + param.jsonstr);
		Map<String,String> contents=new HashMap<String,String>();
		setMemberContent(contents,rec);
		String replace=SqlSentenceHelper.insert(Colums.table, contents);
		Log.e("liu", "sql replace: " + replace);
		try{
			Log.d("debug", "write cache "+rec.cachetype+" "+rec.jsondata);
			m_db.execSQL( replace );
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public void checkCache(int cachetype){
//		if(CacheType.PersonalFeed_Cache==cachetype){
//			// lastest 50
//			//get need delete id
//			List<String> delids=getNeedDelIdByCacheType(CacheType.PersonalFeed_Cache,50);
//			//delete rec
//			deleteRecByIds(delids);
//		}
//		if(CacheType.FeedComment_Cache==cachetype){
//			//lastest 50
//			//get need delete id
//			List<String> delids=getNeedDelIdByCacheType(CacheType.PersonalFeed_Cache,50);
//			//delete rec
//			deleteRecByIds(delids);
//		}
	}
	List<String> getNeedDelIdByCacheType(int cachetype,int limitcount){
		List<String> ids=new ArrayList<String>();
		String get="select "+Colums._id+" from "+Colums.table+" where "+Colums.cachetype+"="+cachetype+" order by "+Colums.time+"asc ";
		try{
			Cursor cur=m_db.rawQuery(get, null);
			if(cur!=null){
				do{
					
					if(cur.getCount()<(limitcount*2)){
						break;
					}
					int idxdel=0;
					if(cur.moveToFirst()){
						do{
							int idx=cur.getColumnIndex(Colums._id);
							String id=cur.getString(idx);
							ids.add(id);
							idxdel++;
							if(idxdel<=limitcount){
								break;
							}
						}while(cur.moveToNext());
					}
				}while(false);
				cur.close();
			}
		}catch(SQLException e){
			
		}
		return ids;
	}
	void deleteRecByIds(List<String> delids){
		if(delids.size()==0){
			return;
		}
		String ids="";
		boolean bfirst=true;
		for(String id:delids){
			if(bfirst){
				ids+=id;
			}else{
				ids+=","+id;
			}
		}
		try{
			
			m_db.execSQL( "delete from "+Colums.table+" where "+Colums._id+" in ("+ids+")" );
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public void clearCache(int type,String identity){
		try{
			
			m_db.execSQL( "delete from "+Colums.table+" where "+Colums.cachetype+"="+type+" and "+
					Colums.identify+" = \""+identity+"\"" );
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public String getCacheData(int cachetype,String identify){
		String rst=null;
		String get="select * from "+Colums.table+" where "+Colums.cachetype+"="+cachetype+" and "+Colums.identify+"=\""+identify+"\"";
		try{
			Cursor cur=m_db.rawQuery(get, null);
			if(cur!=null){
				if(cur.moveToFirst()){
					do{
						int idx=cur.getColumnIndex(Colums.time);
						idx=cur.getColumnIndex(Colums.jsondata);
						rst=cur.getString(idx);
						
					}while(false);
				}
				cur.close();
			}
		}catch(SQLException e){
			
		}
		
		return rst;
//		return null;
	}
	public long getCacheTime(int cachetype,String identify){
		long rst=0;
		String get="select "+Colums.time+" from "+Colums.table+" where "+Colums.cachetype+"="+cachetype+" and "+Colums.identify+"=\""+identify+"\"";
		try{
			Cursor cur=m_db.rawQuery(get, null);
			if(cur!=null){
				if(cur.moveToFirst()){
					do{
						int idx=cur.getColumnIndex(Colums.time);
						rst=cur.getLong(idx);
//						if((System.currentTimeMillis()-time)<300000){
//							break;
//						}
						
						
					}while(false);
				}
				cur.close();
			}
		}catch(SQLException e){
			
		}
		
		return rst;
	}
	
	
	private void setMemberContent(Map<String,String> contents,CacheDataRec rec){
		contents.put( Colums.cachetype, rec.getCachetype());
		contents.put( Colums.identify, rec.getIdentify());
		contents.put( Colums.jsondata, rec.getJsondata());
		contents.put( Colums.time, System.currentTimeMillis()+"");
		
	}
	
}
